package com.example.sh_crosses.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;

import com.example.sh_crosses.MainActivity;
import com.example.sh_crosses.base.BaseActivity;
import com.example.sh_crosses.R;
import com.example.sh_crosses.db.RecordDao;
import com.example.sh_crosses.db.UserDao;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Login extends BaseActivity {
    private final String TAG = Login.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //登录按钮，点击验证字段
        Button btnLogin = findViewById(R.id.login);
        btnLogin.setOnClickListener(v->doCheck());

        //进行注册按钮，点击跳转
        TextView goRegister = findViewById(R.id.goregister);
        goRegister.setOnClickListener(v->{startActivity(new Intent(this,Register.class));finish();});

        updateGameCount();
    }

    /**
     * 验证用户名密码的合法性
     */
    @SuppressLint("DefaultLocale")
    private void doCheck(){
        TextView tvName = findViewById(R.id.username);
        String name = tvName.getText().toString();
        if(TextUtils.isEmpty(name)){
            showShortToast(getResources().getString(R.string.no_empty_username));
            return;
        }
        TextView tvPass = findViewById(R.id.userpass);
        String pass = tvPass.getText().toString();
        if(TextUtils.isEmpty(pass)){
            showShortToast(getResources().getString(R.string.no_empty_password));
            return;
        }

        List<String> list = UserDao.getInstance().query(name,pass);
        showLog(TAG,String.format("list-size:{%d}",list.size()));
        if(list.size()>0){
            showShortToast(getResources().getString(R.string.login_success));
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    startActivity(new Intent(Login.this,MainActivity.class));
                    finish();
                }
            },500);
        }else{
            showShortToast(getResources().getString(R.string.login_failure));
        }

    }
    @Override
    public void onPause() {
        super.onPause();
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_right);
    }

    /**
     * 更新玩游戏的次数
     */
    private void updateGameCount(){
        List<String> list = RecordDao.getInstance().query();
        if(list.size()>0){
            int recordCount = Integer.parseInt(list.get(0));
            recordCount++;
            RecordDao.getInstance().update("1",recordCount);
        }else{
            RecordDao.getInstance().insert(1);
        }
    }
}
